package com.hopu.v1.exception.hander;


import com.hopu.v1.exception.BusinessException;
import com.hopu.v1.exception.NoLoginException;
import com.hopu.v1.pojo.common.R;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.validation.ObjectError;

import java.util.Set;
import java.util.stream.Collectors;

@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    public R constraintViolationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        return R.err(constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(",")));
    }

    @ExceptionHandler(BusinessException.class)
    public R businessException(BusinessException e){ return R.err(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R exception(Exception e){
        e.printStackTrace();
        return R.err(e.getMessage());
    }

    /**
     * token过期异常
     * @param e
     * @return
     */
//    @ExceptionHandler(ExpiredJwtException.class)
//    public R tokenExpiredException(ExpiredJwtException e){
//        return R.err(403, "身份已过期，请重新登录");
//    }

    /**
     * token非法异常
     * @param e
     * @return
     */
    @ExceptionHandler(NoLoginException.class)
    public R NoLoginException(NoLoginException e){
        return R.err(403, e.getMessage());
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        String str = e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining("; "));
        return R.err(str);
    }

}
